<template>
  <div v-show="!isMain && isView" class="view-equip-detail-wrap">
    <px-scrollbar class="view-equip-detail">
      <px-button style="margin: 16px 0 24px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <div style="display: flex; justify-content: space-between">
        <div class="view-equip-title">盘点基本详情</div>
        <px-button v-if="props.isInventory && isStartFlag" type="primary" plain @click="startInventory">开始盘点</px-button>
        <div v-else-if="props.isInventory && !isStartFlag" style="display: flex; align-items: center; justify-content: center; color: #10b981">
          <div style="width: 8px; height: 8px; margin-right: 8px; background: #10b981; border-radius: 8px" />
          盘点执行中
        </div>
      </div>
      <div class="view-equip-wrap">
        <div class="view-equip-content">
          <div class="view-equip-item">
            <div class="label">盘点名称</div>
            <div class="text">{{ formValue.takeStockName || "-" }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">盘点编码</div>
            <div class="text">{{ formValue.takeStockCode || "-" }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">科室</div>
            <div class="text">{{ formValue.classNameDesc || "-" }}</div>
          </div>
        </div>
        <div class="view-equip-content">
          <div class="view-equip-item">
            <div class="label">仓库</div>
            <div class="text">{{ formValue.warehousePositionDesc || "-" }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">盘点负责人</div>
            <div class="text">{{ formValue.takeStockPeopleName || "-" }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">计划日期</div>
            <div class="text">{{ formValue.planStartDate }} - {{ formValue.planEndDate }}</div>
          </div>
        </div>
        <div class="view-equip-content">
          <div class="view-equip-item">
            <div class="label">执行状态</div>
            <div class="text">{{ formValue.executeStatusDesc || "-" }}</div>
          </div>
          <div class="view-equip-item large">
            <div class="label">备注</div>
            <div class="text">{{ formValue.remark || "-" }}</div>
          </div>
        </div>
      </div>
      <div class="view-equip-title">备件盘点表</div>
      <div class="view-equip-wrap view-equip-wrap-second">
        <div class="view-equip-content">
          <div class="view-equip-item plus">
            <div class="label">盘点范围</div>
            <div class="text">{{ formValue.takeStockScope === "all" ? "全面盘点" : "指定盘点" }}</div>
          </div>
          <div v-if="props.isInventory && !isStartFlag" class="view-equip-btn">
            <px-button type="primary" plain @click="downloadInventory"> 盘点表下载 </px-button>
            <px-upload
              style="margin-left: 8px"
              action="/ifp/digitaltwins/api/v1/takeStock/importTakeStockQuantity"
              name="file"
              :headers="headers"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :show-file-list="false"
              :data="{ takeStockId: props.sparePartsId }"
            >
              <px-button type="primary" plain>盘点表导入</px-button>
            </px-upload>
          </div>
        </div>
      </div>
      <px-table :data="formValue.inventoryDetailDTOList" class="equip-table" size="small" height="400" border>
        <px-table-column type="index" label="序号" width="80" align="center" fixed="left" />
        <px-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :label="item.label"
          :min-width="item.minWidth"
          :show-overflow-tooltip="item.showOverflowTooltip"
        >
          <template #default="scope">{{
            scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
          }}</template>
        </px-table-column>
        <px-table-column v-if="props.isInventory && !isStartFlag" prop="takeStockQuantity" label="盘点数量" min-width="140" show-overflow-tooltip>
          <template #header>
            盘点数量
            <px-icon style="cursor: pointer" @click="editQuantity">
              <EditPen />
            </px-icon>
          </template>
          <template #default="scope">
            <div v-if="isQuantity">
              {{ scope.row.takeStockQuantity }}
            </div>
            <px-input-number v-else v-model.number="scope.row.takeStockQuantity" :min="0" size="small" />
          </template>
        </px-table-column>
        <px-table-column v-if="props.isInventory && !isStartFlag" prop="value" label="差额" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <div
              v-if="scope.row.takeStockQuantity - scope.row.currentStock > 0"
              style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; padding: 6px 8px; color: #10b981; background: #e8f8f3"
            >
              {{ scope.row.takeStockQuantity - scope.row.currentStock }}
            </div>
            <div
              v-else-if="scope.row.takeStockQuantity - scope.row.currentStock < 0"
              style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; padding: 6px 8px; color: #f00; background: #ffe5e5"
            >
              {{ scope.row.takeStockQuantity - scope.row.currentStock }}
            </div>
            <div v-else style="color: #000">
              {{ scope.row.takeStockQuantity - scope.row.currentStock }}
            </div>
          </template>
        </px-table-column>
        <px-table-column v-if="props.isInventory && !isStartFlag" prop="sparePartUnitDesc" label="单位" min-width="120" show-overflow-tooltip />
      </px-table>
    </px-scrollbar>
    <div v-show="props.isInventory && !isStartFlag" class="info-form-btns">
      <px-button type="primary" @click="handleSubmit">提交</px-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, toRefs, watch, computed, getCurrentInstance } from "vue";
import { PxMessage } from "px-ui";
import { getToken } from "@/utils/auth";
import { getSparePartsTakeStock, startTakeStock, saveTakeStockQuantity } from "@/api/equip/spareParts";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "isInventory", "sparePartsId"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);
// 页面本身的值
const { proxy }: any = getCurrentInstance();
const state = reactive<any>({
  formValue: {
    id: "",
    takeStockName: "",
    takeStockCode: "",
    classNameDesc: "",
    warehousePositionDesc: "",
    takeStockPeopleName: "",
    planStartDate: "",
    planEndDate: "",
    executeStatusDesc: "",
    remark: "",
    takeStockScope: "all",
    inventoryDetailDTOList: []
  },
  isStartFlag: true,
  isQuantity: true,
  headers: {
    Authorization: "Bearer " + getToken().accessToken || "",
    facCode: localStorage.getItem("facCode") || ""
  },
  tableColumns: [
    { prop: "categoryDesc", label: "种类", minWidth: "120", showOverflowTooltip: true, fixed: "left" },
    { prop: "sparePartName", label: "名称", minWidth: "120", showOverflowTooltip: true },
    { prop: "sparePartCode", label: "编码", minWidth: "120", showOverflowTooltip: true },
    { prop: "typeName", label: "类型", minWidth: "120", showOverflowTooltip: true },
    { prop: "brandName", label: "品牌", minWidth: "120", showOverflowTooltip: true },
    { prop: "supplyModel", label: "厂商型号", minWidth: "120", showOverflowTooltip: true },
    { prop: "model", label: "厂内型号", minWidth: "120", showOverflowTooltip: true },
    { prop: "currentStock", label: "库存量", minWidth: "120", showOverflowTooltip: true },
    { prop: "alarmStock", label: "安全库存量", minWidth: "120", showOverflowTooltip: true },
    { prop: "warehousePositionDesc", label: "库位", minWidth: "120", showOverflowTooltip: true }
  ]
});
const { formValue, isStartFlag, isQuantity, headers, tableColumns } = toRefs(state);
// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && props.isView) {
    const params = {
      id: props.sparePartsId
    };
    const data = await getSparePartsTakeStock(params);
    if (props.isInventory) {
      if (data.executeStatus === 1) {
        // 未开始
        isStartFlag.value = true;
      } else if (data.executeStatus === 2) {
        // 执行中
        isStartFlag.value = false;
      }
    } else {
      isStartFlag.value = true;
    }
    isQuantity.value = true;
    formValue.value.id = data.id;
    formValue.value.takeStockName = data.takeStockName;
    formValue.value.takeStockCode = data.takeStockCode;
    formValue.value.classNameDesc = data.classNameDesc;
    formValue.value.warehousePositionDesc = data.warehousePositionDesc;
    formValue.value.takeStockPeopleName = data.takeStockPeopleName;
    formValue.value.planStartDate = data.planStartDate;
    formValue.value.planEndDate = data.planEndDate;
    formValue.value.executeStatusDesc = data.executeStatusDesc;
    formValue.value.remark = data.remark;
    formValue.value.takeStockScope = data.takeStockScope;
    formValue.value.inventoryDetailDTOList = data.inventoryDetailDTOList;
  } else {
    formValue.value = {
      id: "",
      takeStockName: "",
      takeStockCode: "",
      classNameDesc: "",
      warehousePositionDesc: "",
      takeStockPeopleName: "",
      planStartDate: "",
      planEndDate: "",
      executeStatusDesc: "",
      remark: "",
      takeStockScope: "all",
      inventoryDetailDTOList: []
    };
  }
});
// 返回主页面
const backMainPage = () => {
  emits("backMainPage");
  if (props.isInventory && !isStartFlag.value) {
    emits("queryTable");
  }
};
// 开始盘点
const startInventory = async () => {
  const params = {
    id: props.sparePartsId
  };
  await startTakeStock(params);
  PxMessage({
    type: "success",
    message: "盘点任务激活成功"
  });
  isStartFlag.value = false;
  formValue.value.executeStatusDesc = "执行中";
};
// 编辑数量
const editQuantity = () => {
  isQuantity.value = !isQuantity.value;
};
// 盘点表下载
const downloadInventory = () => {
  const params = {
    id: props.sparePartsId
  };
  proxy.download("post", "/digitaltwins/api/v1/takeStock/templateDownLoad", params, "备件盘点数量模板.xlsx");
};
// 盘点表导入成功状态
const uploadSuccess = async response => {
  if (response.success) {
    PxMessage.success("盘点表导入成功！");
    const params = {
      id: props.sparePartsId
    };
    isQuantity.value = true;
    const data = await getSparePartsTakeStock(params);
    formValue.value.inventoryDetailDTOList = data.inventoryDetailDTOList;
  } else {
    PxMessage.error(response.msg);
  }
};
// 盘点表导入失败状态
const uploadError = error => {
  PxMessage.error(error.msg);
};
// 保存盘点表
const handleSubmit = async () => {
  const arr = [];
  formValue.value.inventoryDetailDTOList.forEach(item => {
    arr.push({
      detailId: item.detailId,
      takeStockQuantity: item.takeStockQuantity
    });
  });
  if (arr && arr.length > 0) {
    const flag = arr.every(item => {
      return item.takeStockQuantity !== "" && item.takeStockQuantity !== null;
    });
    if (!flag) {
      PxMessage.error("您尚有未填写的盘点数量，请填写完成后进行提交！");
      return;
    }
  }
  const params = {
    id: props.sparePartsId,
    takeStockDetailDTOList: arr
  };
  await saveTakeStockQuantity(params);
  PxMessage.success("盘点成功！");
  emits("backMainPage");
  emits("queryTable");
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/view-detail.scss");

.view-equip-detail-wrap {
  position: relative;
  width: 100%;
  height: 100%;

  .view-equip-detail {
    height: calc(100vh - 126px);
  }

  .info-form-btns {
    position: absolute;
    right: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 100%;
    height: 68px;
    padding-right: 34px;
    background: #fff;
    box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
  }
}
</style>
